//
// Created by LiuYou on 2021/10/29.
//

#include <iostream>
#include <cstring>


static const int THREAD_NUM = 20;

static const char* const FILE_NAME = "/tmp/out";

static const int LINE_BUF = 1024;

/*
 * 加入互斥量, 这里使用静态初始化是合适的选择。
 * 互斥量的销毁在 main线程的最后的位置。
 */
static pthread_mutex_t MUTEX = PTHREAD_MUTEX_INITIALIZER;


int main(int argc, char** argv) {

//    FILE_NAME
    pthread_t tidArray[THREAD_NUM]{};
    for (int i = 0; i < THREAD_NUM; ++i) {

        int errorNumber = pthread_create(
                tidArray + i, nullptr,
                [](void* args) -> void* {

                    FILE* fp = fopen( FILE_NAME, "r+" );
                    if (fp == nullptr) {
                        perror( "fopen()" );
                        pthread_exit( nullptr );
                    }
                    pthread_cleanup_push( [](void* args) {
                        fclose((FILE*) args );
                    }, fp );
                    pthread_cleanup_pop( 1 );

                    pthread_mutex_lock( &MUTEX );
                    char lineBuf[LINE_BUF]{};
                    fgets( lineBuf, LINE_BUF, fp );

                    // 把文件指针定位到文件开始处。
                    fseek( fp, 0, SEEK_SET );
                    fprintf( fp, "%d\n", (atoi( lineBuf ) + 1));
                    fflush( fp );
                    pthread_mutex_unlock( &MUTEX );


                    pthread_exit( nullptr );
                },
                nullptr );
        if (errorNumber != 0) {
            fprintf( stderr, "pthread_create(): %s.\n", strerror( errorNumber ));
            return 1;
        }


    }


    for (int i = 0; i < THREAD_NUM; ++i) {
        pthread_join( tidArray[i], nullptr );
    }


    pthread_mutex_destroy( &MUTEX );


    return 0;
}
